import axios from 'axios';

import { v4 as uuid } from 'uuid';

const getRequestId = () => {
  const time = `${new Date().getTime()}`.split('').reverse().join('');
  const time1 = time.substring(0, 3);
  const time2 = time.substring(3, 7);
  const time3 = time.substring(7);
  const id = uuid().replace(/-/g, '');
  const uuid1 = id.substring(0, 12);
  const uuid2 = id.substring(12);

  return time1 + uuid1 + time2 + uuid2 + time3;
};

const createAxios = () => {
  const fetch = axios.create({});
  fetch.defaults.baseURL = process.env.VUE_APP_HTTP_BASE_URL;
  // fetch.interceptors.response.use(null, (error) => {});
  fetch.defaults.headers = {
    Authorization: `bearer 838cea87-5ebd-4a96-a091-ddef911d5f19`,
    'H-Request-Id': getRequestId(),
  };


  fetch.interceptors.response.use((data) => {
    console.log('fetch response data = ', data)
    return data.data
  }, (error) => {
    if (error) {
      const { response } = error
      const status = response?.status
      if (status === 401) {
        // 当接口返回401时重新刷新token
        console.log('401')
        return Promise.reject({ code: 401 })
      }
      return Promise.reject(error)
    }
  })

  return fetch;
};
export { createAxios };
